package com.iflyun.rabbitmq.service;

import java.io.UnsupportedEncodingException;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.support.converter.AbstractMessageConverter;
import org.springframework.amqp.support.converter.MessageConversionException;

import com.alibaba.fastjson.JSON;

public class MessageConverter  extends AbstractMessageConverter {

	public static final String DEFAULT_CHARSET = "UTF-8";
	
	private volatile String defaultCharset = DEFAULT_CHARSET;
	
	@Override
	protected Message createMessage(Object objectToConvert, MessageProperties messageProperties) {
		byte[] bytes = null;
        try {
//        	使用fastjson将消息转成string
            String jsonString = JSON.toJSONString(objectToConvert);
//          将消息转成bytes数组
            bytes = jsonString.getBytes(this.defaultCharset);
        } catch (UnsupportedEncodingException e) {
//        	转换失败抛出异常
            throw new MessageConversionException(
                    "Failed to convert Message content", e);
        } 
        messageProperties.setContentType(MessageProperties.CONTENT_TYPE_JSON);
        messageProperties.setContentEncoding(this.defaultCharset);
        if (bytes != null) {
            messageProperties.setContentLength(bytes.length);
        }
        return new Message(bytes, messageProperties);
	}


	@SuppressWarnings("unchecked")
	public <T> T fromMessage(Message message,T t)  {
		// TODO Auto-generated method stub
		 String json = "";
	        try {
	            json = new String(message.getBody(),defaultCharset);
	        } catch (UnsupportedEncodingException e) {
	            e.printStackTrace();
	        }
	     return  (T) JSON.parseObject(json, t.getClass()); 
	}


	@Override
	public Object fromMessage(Message arg0) throws MessageConversionException {
		// TODO Auto-generated method stub
		return null;
	}
	
	public void setDefaultCharset(String defaultCharset) {
        this.defaultCharset = (defaultCharset != null) ? defaultCharset
                : DEFAULT_CHARSET;
    }


	public MessageConverter() {
		super();
		// TODO Auto-generated constructor stub
	}

	
	
}
